package com.bizframework.core.serialization.xstream;

import java.sql.Timestamp;
import java.util.Date;

import com.bizframework.core.serialization.ObjectSerializer;
import com.bizframework.core.serialization.xstream.converter.DateConverter;
import com.bizframework.core.util.StringUtils;
import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.converters.Converter;
import com.thoughtworks.xstream.io.xml.DomDriver;


public class XStreamObjectXMLSerializer implements ObjectSerializer {
	
	protected XStream xStream;

	public XStreamObjectXMLSerializer() {
		xStream = new XStream(new DomDriver("GB2312"));
		xStream.registerConverter(new DateConverter());
		xStream.addDefaultImplementation(Date.class, Timestamp.class);
	}

	/**
	 * 序列化对象
	 * 
	 * @param obj 需要序列化的对象
	 * @return 序列话后的字符串
	 * @throws Exception
	 */
	public String serialize(Object obj) {
		String result = new String();
		if (obj == null) {
			return result;
		}

		result = xStream.toXML(obj);
		return result;
	}

	/**
	 * 反序列化对象
	 * 
	 * @param type
	 *            对象类型
	 * @param serializedString
	 *            已序列化的对象字符串
	 * @return 对象
	 * @throws Exception
	 */
	@SuppressWarnings( { "unchecked" })
	public <T> T deserialize(Class<T> type, String serializedString) {
		if (StringUtils.isNullOrEmpty(serializedString) || type == null) {
			return null;
		}

		Object result = xStream.fromXML(serializedString);
		return (T) result;
	}

	public void addAlias(String name, Class<?> type){
		xStream.alias(name, type);
	}
	
	public void addAttribute(String name, Class<?> type){
		xStream.useAttributeFor(name, type);
	}
	
	public void addImplicitCollection(String name, Class<?> type){
		xStream.useAttributeFor(name, type);
	}

	public void addDefaultImplementation(Class<?> defaultImplementation, Class<?> ofType) {
		xStream.addDefaultImplementation(defaultImplementation, ofType);
	}
	
	public void registerConverter(Converter converter){
		xStream.registerConverter(converter);
	}
}
